﻿using System;
using System.Collections.Generic;
using Model;

namespace Hotfix
{
    public class MessageHandlerHelper : Singleton<MessageHandlerHelper>
    {

        Dictionary<Opcode, List<IMessageHandler>> dicOpcodeMassageHander = new Dictionary<Opcode, List<IMessageHandler>>();

        public void InitStart()
        {
            Type[] types = GetType().Assembly.GetTypes();

            foreach (var item in types)
            {
                object[] obj = item.GetCustomAttributes(typeof(MessagerAttribute), false);
                MessageHandlerAttribute massageHandlerHelper = obj[0] as MessageHandlerAttribute;
                if (massageHandlerHelper == null) continue;

                if (item == typeof(IMessageHandler))
                {
                    IMessageHandler messageHandler = Activator.CreateInstance(item) as IMessageHandler;
                    if (messageHandler == null) continue;

                    List<IMessageHandler> list;

                    if (!dicOpcodeMassageHander.TryGetValue(massageHandlerHelper.opcode, out list))
                    {
                        list = new List<IMessageHandler>();
                        dicOpcodeMassageHander[massageHandlerHelper.opcode] = list;
                    }
                    list.Add(messageHandler);

                }

            }
        }

        public List<IMessageHandler> OpcodeToObject(Opcode opcode)
        {
            List<IMessageHandler> list;
            if (!dicOpcodeMassageHander.TryGetValue(opcode, out list)) return null;

            return list;
        }
    }
}
